package com.jdd.modules.parkmonthly.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jdd.common.api.vo.Result;
import com.jdd.common.constant.JddConstant;
import com.jdd.common.util.DateUtil;
import com.jdd.common.util.SnowFlakeUtil;
import com.jdd.modules.configcartype.entity.ConfigCarType;
import com.jdd.modules.parkcar.entity.ParkCarMonthly;
import com.jdd.modules.parkcar.entity.ParkSpace;
import com.jdd.modules.parkcar.service.IParkCarMonthlyService;
import com.jdd.modules.parkcar.service.IParkSpaceService;
import com.jdd.modules.parking.entity.ParkCarEnterLog;
import com.jdd.modules.parking.service.IConfigParkInfoService;
import com.jdd.modules.parking.service.IparkCarEnterLogService;
import com.jdd.modules.parkmonthly.entity.MonthlyCarConfig;
import com.jdd.modules.parkmonthly.entity.MonthlyCarTypeConvert;
import com.jdd.modules.parkmonthly.entity.MonthlyCardInfo;
import com.jdd.modules.parkmonthly.entity.MonthlyPackageInfo;
import com.jdd.modules.parkmonthly.service.IMonthlyCarTypeConvertService;
import com.jdd.modules.parkmonthly.service.IMonthlyCardInfoService;
import com.jdd.modules.parkmonthly.service.IMonthlyPackageInfoService;
import com.jdd.modules.parkmonthly.service.IRemoveMonthlyCardInfoService;
import com.jdd.modules.sdkidentifyresultpushlog.entity.vo.ParkCarEnterLogSyncV3Vo;
import com.jdd.modules.sdkidentifyresultpushlog.service.ISdkIdentifyResultPushLogV3Service;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 注销月卡
 * @Author: qilina
 * @Date: 2022-01-08
 * @Version: V1.0
 */
@Service
@Slf4j
public class RemoveMonthlyCardInfoServiceImpl implements IRemoveMonthlyCardInfoService {

    @Resource
    private IMonthlyCarTypeConvertService iMonthlyCarTypeConvertService;
    @Resource
    private IMonthlyPackageInfoService iMonthlyPackageInfoService;
    @Resource
    private IparkCarEnterLogService iparkCarEnterLogService;
    @Resource
    private IParkCarMonthlyService iParkCarMonthlyService;
    @Resource
    private IParkSpaceService parkSpaceService;
    @Resource
    private IMonthlyCardInfoService iMonthlyCardInfoService;
    @Resource
    private IConfigParkInfoService configParkInfoService;
    @Resource
    private ISdkIdentifyResultPushLogV3Service sdkIdentifyResultPushLogV3Service;



    @Override
    @CacheEvict(value = {"monthly:cardAndPackage"}, allEntries = true)
    public Result getMonthlyCardConcel(MonthlyCardInfo monthlyCardInfo1) {

        log.info("注销月卡信息，传入参数--------------------------》:{}", monthlyCardInfo1);
        boolean resFlag = true;
        // 新增月卡成功判断是否启用月租车下发功能

        MonthlyCardInfo monthlyCardInfo = iMonthlyCardInfoService.getById(monthlyCardInfo1.getId());
        monthlyCardInfo.setMonthlyMoney(monthlyCardInfo1.getMonthlyMoney());
        monthlyCardInfo.setRemark(monthlyCardInfo1.getRemark());
        QueryWrapper<MonthlyCarConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("park_code", monthlyCardInfo.getParkCode());
        MonthlyPackageInfo monthlyPackageInfo = iMonthlyPackageInfoService.getById(monthlyCardInfo.getPackageId());
        log.info("注销月卡信息，查询月套餐信息--------------------------》:{}", monthlyPackageInfo);

        // 判断是否有在场车辆
        List<ParkCarEnterLog> parkCarEnterLogs = getPlateNoInPark(monthlyCardInfo.getParkCode(), monthlyCardInfo.getId());
        List<ParkCarEnterLog> parkCarEnterLogList = new ArrayList<>();
        List<MonthlyCarTypeConvert> monthlyCarTypeConverts = new ArrayList<>();
        log.info("查询在场记录信息为ssss--------------------------》:{}", parkCarEnterLogs);
        // 若存在入场记录，则生成一条注销时间的临时记录
        if (parkCarEnterLogs.size() > 0) {
            for (ParkCarEnterLog parkCarEnterLog : parkCarEnterLogs) {
            	 // 若为欲转卡，直接出场
                if ("1".equals(parkCarEnterLog.getIsTransfer())){
                    parkCarEnterLog.setIsOut("1");
                    iparkCarEnterLogService.updateById(parkCarEnterLog);
                    continue;
                }
                parkCarEnterLog.setId(SnowFlakeUtil.getId());
                parkCarEnterLog.setCarNature(JddConstant.StringNumber.STRING_ZERO);
                // 判断月租是否过期,过期
                if (monthlyCardInfo.getEndTime().before(new Date())) {
                    // 判断入场是否过期
                    if (DateUtil.fomatDateTime(parkCarEnterLog.getCarEnterTime()).before(monthlyCardInfo.getEndTime())) {
                        parkCarEnterLog.setCarEnterTime(DateUtil.fomatDateTimeStr(monthlyCardInfo.getEndTime()));
                    } else {
                        continue;
                    }
                } else {
                    // 未过期
                    parkCarEnterLog.setCarEnterTime(DateUtil.fomatDateTimeStr(new Date()));
                }
                ConfigCarType configCarType = iMonthlyCardInfoService.getCarType(parkCarEnterLog.getParkCode(), Integer.valueOf(parkCarEnterLog.getCarTypeNo()));
                if (null != configCarType) {
                    parkCarEnterLog.setCarTypeId(configCarType.getId());
                    parkCarEnterLog.setCarTypeName(configCarType.getCarTypeName());
                }
                parkCarEnterLog.setParkNumber("");
                parkCarEnterLog.setMonthlyCardId("");
                parkCarEnterLog.setCreateTime(new Date());
                //组装转卡记录
                MonthlyCarTypeConvert monthlyCarTypeConvert = iMonthlyCardInfoService.getMonthlyCarTypeConvert(monthlyCardInfo, parkCarEnterLog, monthlyPackageInfo);
                monthlyCarTypeConverts.add(monthlyCarTypeConvert);
                parkCarEnterLogList.add(parkCarEnterLog);
            }
            log.info("生成入场记录信息为--------------------------》:{}", parkCarEnterLogs);
            if(parkCarEnterLogList.size() > 0){
            	resFlag = iparkCarEnterLogService.saveBatch(parkCarEnterLogList);
            	try {
    				for(ParkCarEnterLog parkCarEnterLog : parkCarEnterLogList){
    					ParkCarEnterLogSyncV3Vo entity = new ParkCarEnterLogSyncV3Vo();
    					entity.setParkCarEnterLogStr(JSON.toJSONString(parkCarEnterLog));
    					// 月租车
    					if(StringUtils.isNotBlank(parkCarEnterLog.getParkNumber())){
    						entity.setParkStatus(JddConstant.ParkSpace.PARKSTATUS_ONE);
    						entity.setSourceAreaId(parkCarEnterLog.getAreaId());
    					}else{
    						// 临时车
    						entity.setParkStatus(JddConstant.ParkSpace.PARKSTATUS_ZERO);
    					}
                        String url = "";
    					sdkIdentifyResultPushLogV3Service.sendMessageV3(entity,url);
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    				log.info("注销月租车上传到云端失败->{}",e);
    			}
            }

            if (!resFlag) {
                return Result.error("新增转卡失败！");
            }
            resFlag = iMonthlyCarTypeConvertService.saveBatch(monthlyCarTypeConverts);
            if (!resFlag) {
                return Result.error("新增转卡失败！");
            }
        }
        monthlyCardInfo.setMonthlyStatus(JddConstant.IntNumber.INT_THREE);
        monthlyCardInfo.setUpdateTime(new Date());
        resFlag = iMonthlyCardInfoService.updateById(monthlyCardInfo);
        if (!resFlag) {
            return Result.error("更新月卡为注销状态失败！");
        }
        // 4.还原车位绑定
        QueryWrapper<ParkSpace> parkSpaceQueryWrapper = new QueryWrapper<>();
        parkSpaceQueryWrapper.eq("monthly_card_id", monthlyCardInfo.getId());
        parkSpaceQueryWrapper.eq("status", "Y");
        List<ParkSpace> parkSpaceList = parkSpaceService.list(parkSpaceQueryWrapper);

        if (parkSpaceList.size() > 0) {
            for (ParkSpace parkSpace : parkSpaceList) {
                parkSpace.setParkStatus(JddConstant.StringNumber.STRING_ZERO);
                parkSpace.setMonthlyCode("");
                parkSpace.setAddress("");
                parkSpace.setUserName("");
                parkSpace.setMobile("");
                parkSpace.setMonthlyCardId("");
                parkSpace.setStartTime(null);
                parkSpace.setEndTime(null);
                parkSpace.setPlateNo("");
                parkSpace.setParkStatus(JddConstant.StringNumber.STRING_ZERO);
                //resFlag = parkSpaceService.updateById(parkSpace);
//                if (!resFlag) {
//                    return Result.error("更新车位失败！");
//                }
            }
            parkSpaceService.updateBatchParkSpaceById(parkSpaceList);
        }
        // 5.月租车信息
        QueryWrapper<ParkCarMonthly> wrapper = new QueryWrapper<>();
        wrapper.eq("park_code", monthlyCardInfo.getParkCode());
        wrapper.eq("monthly_card_id", monthlyCardInfo.getId());
        iParkCarMonthlyService.remove(wrapper);
        // 6.新增月卡操作记录
        resFlag = iMonthlyCardInfoService.getMonthlyCardEditInfo(monthlyCardInfo, JddConstant.StringNumber.STRING_THREE);
        if (!resFlag) {
            return Result.error("新增月卡操作记录失败！");
        }
        return Result.ok("注销成功！");
    }

    /**
     * 注销时 查询绑定月租车车牌号 是否有在场的入场记录
     *
     * @return
     * @author qilina
     */
    private List<ParkCarEnterLog> getPlateNoInPark(String parkCode, String monthlyCardId) {
        // 查询月卡绑定的区域信息和车位信息
        List<ParkCarMonthly> parkCarMonthlyList = getPlateNoInfo(monthlyCardId);
        List<String> areaList = parkCarMonthlyList.stream().map(ParkCarMonthly::getAreaId).distinct().collect(Collectors.toList());
        log.info("查询区域信息，areaList--------------------------》:{}", areaList);
        List<String> plateNos = parkCarMonthlyList.stream().map(ParkCarMonthly::getPlateNo).distinct().collect(Collectors.toList());
        QueryWrapper<ParkCarEnterLog> parkCarEnterLogQueryWrapper = new QueryWrapper<>();
        parkCarEnterLogQueryWrapper.eq("park_code", parkCode);
        parkCarEnterLogQueryWrapper.eq("monthly_card_id", monthlyCardId);
        parkCarEnterLogQueryWrapper.eq("is_out", JddConstant.StringNumber.STRING_ZERO);
        parkCarEnterLogQueryWrapper.in("plate_no", plateNos);
        parkCarEnterLogQueryWrapper.in("area_id", areaList);
        parkCarEnterLogQueryWrapper.orderByAsc("car_enter_time");
        List<ParkCarEnterLog> list = iparkCarEnterLogService.list(parkCarEnterLogQueryWrapper);
        Map<String, ParkCarEnterLog> newMap = new HashMap(16);
        for (ParkCarEnterLog parkCarEnterLog : list) {
            newMap.put(parkCarEnterLog.getPlateNo(), parkCarEnterLog);
        }
        List<ParkCarEnterLog> carEnterLogs = new ArrayList<>();
        for (String key : newMap.keySet()) {
            carEnterLogs.add(newMap.get(key));
        }
        return carEnterLogs;
    }


    /**
     * 月卡新信息
     *
     * @param id
     * @return
     */
    public List<ParkCarMonthly> getPlateNoInfo(String id) {
        QueryWrapper<ParkCarMonthly> parkCarMonthlyQueryWrapper = new QueryWrapper<>();
        parkCarMonthlyQueryWrapper.select("DISTINCT(plate_no) AS plateNo", "area_id AS areaId");
        parkCarMonthlyQueryWrapper.eq("monthly_card_id", id);
        List<ParkCarMonthly> parkCarMonthlyList = iParkCarMonthlyService.list(parkCarMonthlyQueryWrapper);
        return parkCarMonthlyList;
    }


}
